package com.mangatta.cloud.ec2;

import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Tag;

import java.util.List;

public class Ec2Instance {
    private final String instanceId;
    private final String name;
    private final long state;

    public Ec2Instance(String instanceId, String name, long state) {
        this.instanceId = instanceId;
        this.name = name;
        this.state = state;
    }

    @SuppressWarnings("unchecked")
    public static Ec2Instance getEc2Instance(Instance instance) {
        if (instance == null) {
            return null;
        }
        long state = instance.getState().getCode();

        String instanceName = "No-Name";
        List<Tag> tags = (List<Tag>) instance.getTags();
        if (tags != null && tags.size() > 0 && tags.get(0) != null) {
            instanceName = tags.get(0).getValue();
        }

        return new Ec2Instance(instance.getInstanceId(), instanceName, state);
    }

    public String getInstanceId() {
        return instanceId;
    }

    public String getName() {
        return name;
    }

    public long getState() {
        return state;
    }

    public boolean isActive() {
        return (state & 16) != 0;
    }

    @Override
    public String toString() {
        return String.format("Instance Id: %s, Instance name: %s, State: %d", instanceId, name, state);
    }
}
